package com.app.reptile.tasks;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v132.network.Network;
import org.openqa.selenium.devtools.v132.network.model.Headers;
import org.openqa.selenium.devtools.v132.network.model.ResponseReceived;
import org.openqa.selenium.net.PortProber;

import java.io.File;
import java.util.Optional;

/**
 * Selenium 爬虫工具
 */
public abstract class AbstractSeleniumV133Task extends AbstractTask {

    protected abstract void start(ChromeDriver chromeDriver) throws Exception;

    protected int port;

    protected void listenerRequest(DevTools devTools, ResponseReceived responseReceived){

    }
    @Override
    protected void start() throws Exception {

        String dir = "D:\\code\\java\\cat-jdf";//System.getProperty("user.dir");
        String os = System.getProperty("os.name");
        File driverPath = new File(dir,"linux\\chromedriver\\chromedriver");
        //"C:\\Users\\Administrator\\Desktop\\133.0.6943.53\\chromedriver-linux64\\chromedriver";
        File chromePath = new File(dir,"linux\\chrome\\chrome");
        //"C:\\Users\\Administrator\\Desktop\\133.0.6943.53\\chrome-linux64\\chrome";

        if (os.toLowerCase().contains("windows")){
            driverPath = new File(dir,"win\\chromedriver\\chromedriver.exe");// "C:\\Users\\Administrator\\Desktop\\133.0.6943.53\\chromedriver-win64\\chromedriver.exe";
            chromePath = new File(dir,"win\\chrome\\chrome.exe");// "C:\\Users\\Administrator\\Desktop\\133.0.6943.53\\chrome-win64\\chrome.exe";
        }
        logger.info("chromedriver路径:{} chrome路径:{}",driverPath.getAbsolutePath(),chromePath.getAbsolutePath());
        if (!driverPath.exists() || !chromePath.exists()){
            throw new RuntimeException("chromedriver 或 chrome 核心文件不存在");
        }

        this.port = PortProber.findFreePort();
        File profile = new File("\\selenium\\profile"+this.port);
        if (os.toLowerCase().contains("windows")){
            profile = new File("C:\\selenium\\profile"+this.port);
        }

        if (!profile.exists()){
            profile.mkdirs();
        }

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--disable-web-security");
        chromeOptions.setBinary(chromePath);
//        chromeOptions.setExperimentalOption("debuggerAddress", "localhost:"+port);


        ChromeDriverService driverService = new ChromeDriverService.Builder().usingDriverExecutable(driverPath).usingPort(this.port).build();

        ChromeDriver chromeDriver = new ChromeDriver(driverService,chromeOptions);

        //设置超时，避免有些内容加

        DevTools devTools = chromeDriver.getDevTools();
        devTools.createSession();
        //监听网络数据的功能
        devTools.addListener(Network.responseReceived(), responseReceived -> {
            String url = responseReceived.getResponse().getUrl();
            Headers headers = responseReceived.getResponse().getHeaders();
//            Network.GetResponseBodyResponse responseBodyResponse = devTools.send(Network.getResponseBody(responseReceived.getRequestId()));
//            String body = responseBodyResponse.getBody();
            logger.info("reptile请求地址:{},请求头:{}",url, headers.toString());
            listenerRequest(devTools,responseReceived);
        });
        devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

        try{
            start(chromeDriver);
        }catch (Exception e){
            logger.error("系统错误",e);
        }finally {
            devTools.disconnectSession();
            chromeDriver.close();//关闭全部窗口
            chromeDriver.quit();//正常还需要调用次函数 关闭了全部chromeDriver也会消失
            driverService.stop();
        }
    }

}
